package com.micro.controller;

import com.micro.dto.TrainOrderDTO;
import com.micro.dto.TrainMealOrderDTO;
import com.micro.entity.HotelOrder;
import com.micro.service.HotelOrderService;
import com.micro.service.TrainMealOrderService;
import com.micro.service.TrainTicketOrderService;
import com.micro.client.UserServiceClient;
import com.micro.client.HotelServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private TrainTicketOrderService trainTicketOrderService;
    
    @Autowired
    private TrainMealOrderService trainMealOrderService;
    
    @Autowired
    private HotelOrderService hotelOrderService;
    
    @Autowired
    private UserServiceClient userServiceClient;
    
    @Autowired
    private HotelServiceClient hotelServiceClient;

    // 获取用户的所有订单汇总
    @GetMapping("/user/{username}/summary")
    public ResponseEntity<List<TrainOrderDTO>> getUserOrderSummary(@PathVariable String username) {
        try {
            // 直接返回火车票订单列表
            List<TrainOrderDTO> trainOrders = trainTicketOrderService.getOrderDTOsByUsername(username);
            return ResponseEntity.ok(trainOrders);
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("获取用户订单失败: " + e.getMessage());
            e.printStackTrace();
            // 返回空列表而不是400错误
            return ResponseEntity.ok(new ArrayList<>());
        }
    }

    // 获取用户的所有火车票订单
    @GetMapping("/user/{username}/train-tickets")
    public ResponseEntity<List<TrainOrderDTO>> getUserTrainTicketOrders(@PathVariable String username) {
        try {
            List<TrainOrderDTO> orders = trainTicketOrderService.getOrderDTOsByUsername(username);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 获取用户的所有火车餐订单
    @GetMapping("/user/{username}/train-meals")
    public ResponseEntity<List<TrainMealOrderDTO>> getUserTrainMealOrders(@PathVariable String username) {
        try {
            List<TrainMealOrderDTO> orders = trainMealOrderService.getOrdersByUsername(username);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    // 获取火车餐订单详情
    @GetMapping("/train-meals/{orderId}/details")
    public ResponseEntity<com.micro.entity.TrainMealOrder> getTrainMealOrderDetails(@PathVariable Long orderId) {
        try {
            com.micro.entity.TrainMealOrder order = trainMealOrderService.getOrderDetails(orderId);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 获取用户的所有酒店订单
    @GetMapping("/user/{username}/hotels")
    public ResponseEntity<List<HotelOrder>> getUserHotelOrders(@PathVariable String username) {
        try {
            // 先通过用户名获取用户ID
            UserServiceClient.UserDTO user = userServiceClient.getUserByUsername(username);
            if (user == null) {
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            List<HotelOrder> orders = hotelOrderService.getOrdersByUserId(user.getUserId());
            
            // 为每个订单添加酒店名称信息
            for (HotelOrder order : orders) {
                try {
                    // 通过酒店服务获取酒店信息
                    HotelServiceClient.HotelDTO hotel = hotelServiceClient.getHotelById(order.getHotelId());
                    if (hotel != null) {
                        order.setHotelName(hotel.getHotelName());
                    }
                } catch (Exception e) {
                    // 如果获取酒店信息失败，继续处理其他订单
                    logger.warn("获取酒店信息失败，酒店ID: {}", order.getHotelId());
                }
            }
            
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 获取订单统计信息
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getOrderStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 这里可以添加各种统计信息
            // 例如：总订单数、各类型订单数量、收入统计等
            
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
